package edu.must.uh.servlet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import edu.must.uh.impl.SharesImpl;
import edu.must.uh.util.HttpClientResult;
import edu.must.uh.util.HttpClientUtils;
import edu.must.uh.util.R;
import edu.must.uh.util.ServletUtils;
import edu.must.uh.util.Tools;
import edu.must.uh.util.ToolsOfString;

@WebServlet("/SharesServlet")
public class SharesServlet extends BaseServlet {
    
    private static final long serialVersionUID = 12197442526341123L;
    private static Logger logger = Logger.getLogger(RegCodeServlet.class); 
    SharesImpl baseImpl = new SharesImpl();    
    public Object getList(HttpServletRequest request, HttpServletResponse response) throws Exception {      
     
        Map<String, Object> searchcondition = ServletUtils.getsearchcondition(request);
        List<Map<String,Object>> resList = baseImpl.getlist(searchcondition, "");  
        if(resList != null && !resList.isEmpty()) 
        {
            for (Map<String,Object> e:resList) {
                String sharesid = ToolsOfString.NulltoEmpty(e.get("SHAREID"));
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/json; charset=utf-8");             
                String url = "http://hq.sinajs.cn/list=sz"+sharesid;
                if(sharesid.startsWith("6")) {
                     url = "http://hq.sinajs.cn/list=sh"+sharesid;
                }
                HttpClientResult result = HttpClientUtils.doGet(url, params, null); 
                if (result.getCode() == 200) { 
                    String[] Content = result.getContent().toString().split("=\"")[1].split(",");
                    Float price = Float.parseFloat(Content[3]);
                    Float yesterdayClose = Float.parseFloat(Content[2]);                    
                    e.put("todayOpen", Content[1]);
                    e.put("yesterdayClose",yesterdayClose);
                    e.put("price", price);
                    e.put("balance",String.format("%.2f",  price -yesterdayClose));
                    e.put("percentage",String.format("%.2f", (price / yesterdayClose -1)*100) + "%");
                    
                    e.put("num", Content[8]);
                    e.put("priceTotal", Content[9]);
                    e.put("strdate", Content[30]);
                    e.put("strtime", Content[31]);                   
                   
                }
            }
        }
        return R.succ(resList);         
    }
    

    
    public Object getOneData(HttpServletRequest request, HttpServletResponse response) throws Exception { 
    	String keyValue =ToolsOfString.NulltoEmpty(request.getParameter("ID")); 
    	String sqlString = "SELECT  RoleId, Type,FullName,SortCode FROM base_role Where DeleteMark= 0  ";
    	sqlString = sqlString + " AND RoleId = '"+keyValue+"'";
        Map<String,Object>  map = baseImpl.getMap(sqlString);                 
        return R.succ(map);         
    }
    
    
    public Object getSharesData(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        String FUNDSID =ToolsOfString.NulltoEmpty(request.getParameter("FUNDSID")); 
  
        String url = "http://fund.eastmoney.com/pingzhongdata/"+FUNDSID+".js?v=20160518155842"  ;
      
        Map<String, String> params = new HashMap<String, String>();
        params.put("Content-Type", "application/json; charset=utf-8");   
        HttpClientResult result = HttpClientUtils.doGet(url, params, null); 
        if (result.getCode() == 200) {  
            String Content = result.getContent().toString();
            
            String[] stocks = Content.split(";");
            String stockCodesNew = stocks[8];
            if(Tools.notEmpty(stockCodesNew)) {
               
                String[] stockCodesNews = stockCodesNew.replace("\"]", "").split("\",\"");
                List<String> Sharesids = new ArrayList<String>();
                for (int i = 0; i < stockCodesNews.length; i++) {
                    String s= stockCodesNews[i];
                    String e = s.substring(s.length()-6,s.length());
                    Sharesids.add(e);
                }
                List<Map<String, Object>> res = getSharesList(Sharesids);
                
                return R.succ(res);  
            }
        }                   
        return R.fail("無此數據");         
    }
    
    public List<Map<String, Object>> getSharesList(List<String> Sharesids ) throws Exception{
        List<Map<String, Object>> resList = new ArrayList<Map<String,Object>>();
        for (String sharesid : Sharesids) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/json; charset=utf-8");             
            String url = "http://hq.sinajs.cn/list=sz"+sharesid;
            if(sharesid.startsWith("6")) {
                 url = "http://hq.sinajs.cn/list=sh"+sharesid;
            }
            HttpClientResult result = HttpClientUtils.doGet(url, params, null); 
            if (result.getCode() == 200) { 
                String[] Content = result.getContent().toString().split("=\"")[1].split(",");
                Map<String, Object> e =new HashMap<String, Object>();
                e.put("sharesid", sharesid);
                e.put("name", Content[0]);
                e.put("todayOpen", Content[1]);
                e.put("yesterdayClose", Content[2]);
                e.put("price", Content[3]);
                e.put("num", Content[8]);
                e.put("priceTotal", Content[9]);
                e.put("strdate", Content[30]);
                e.put("strtime", Content[31]);
                resList.add(e);
            }
        }
        return resList;
    }
    
    public Object getAPIFunds(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        String funds =ToolsOfString.NulltoEmpty(request.getParameter("funds"));      
        String url = "http://fundgz.1234567.com.cn/js/"+funds+".js?rt=1463558676006"  ;
      
        Map<String, String> params = new HashMap<String, String>();
        params.put("Content-Type", "application/json; charset=utf-8");   
        HttpClientResult result = HttpClientUtils.doGet(url, params, null);             
        logger.info("請求gov預約信息：result==" + result.toString());
        if (result.getCode() == 200) {  
            String Content = result.getContent().toString().replace("jsonpgz(", "").replace(");", "");
            if(Tools.notEmpty(Content)) {
                return R.succ(Content);  
            }
        }                   
        return R.fail("無此數據");         
    }
    
    
    
    public Object delete(HttpServletRequest request, HttpServletResponse response) throws Exception {   
        String sharesid =ToolsOfString.NulltoEmpty(request.getParameter("SHAREID")); 
        Map<String, Object> searchcondition = new HashMap<String, Object>();
        searchcondition.put("SHAREID", sharesid);        
        Integer resInteger = baseImpl.deleteByCondition(searchcondition);
        return R.succ(resInteger);         
    }
    
  public Object save(HttpServletRequest request, HttpServletResponse response) throws Exception {  
      		
		String sql = "";
		Map<String, Object> searchcondition = ServletUtils.getsearchcondition(request);
	    String ID =ToolsOfString.NulltoEmpty(searchcondition.get("ID"));	    
        String FUNDSID =ToolsOfString.NulltoEmpty(searchcondition.get("FUNDSID")); 
        String SHAREID =ToolsOfString.NulltoEmpty(searchcondition.get("SHAREID"));
        String FullName =ToolsOfString.NulltoEmpty(searchcondition.get("FullName"));
        FullName =  java.net.URLDecoder.decode(FullName, "UTF-8");      
        
        if(Tools.notEmpty(ID)) {
        	//sql = "UPDATE base_role  SET FUNDSID = '"+FUNDSID+"',FullName = '"+FullName+"',SortCode = '" +SortCode+"'";
        	sql = sql + " WHERE ID ='"+ID+"'"; 
        }else {    
        	sql = "INSERT INTO shares(FUNDID,SHAREID,FULLNAME)VALUES";
        	sql = sql + " ('"+FUNDSID+"','"+SHAREID+"','"+FullName+"')"; 
        }
        Integer resInteger = baseImpl.save(sql);
        if(resInteger == 1) {
        	   return R.succ(); 
        }
        return R.fail();
       
    }
    
    
    
   
}
